import React, { useEffect, useState } from 'react';
import { Form, Input } from '@alifd/next';
import store from '@/store';
import { getUUID } from '@/utils';
import styles from '../index.module.scss';

export default () => {
  const [uuid, setUuid] = useState(getUUID());
  const [userState, userDispatchers] = store.useModel('user');
  useEffect(() => {
    userDispatchers.fetchCaptcha({ uuid });
  }, [userDispatchers, uuid]);
  const handleLogin = (values, errors) => {
    if (errors === null) {
      userDispatchers.fetchLogin({ ...values, uuid });
    }
    setUuid(getUUID());
  };

  return (
    <div className={styles.content}>
      <div className={styles.formContainer}>
        <h4 className={styles.formTitle}>登录</h4>
        <Form>
          <Form.Item className={styles.formItem} required help={false}>
            <Input className={styles.input} size="large" name="username" placeholder="用户名" />
          </Form.Item>
          <Form.Item className={styles.formItem} required help={false}>
            <Input.Password className={styles.input} size="large" name="password" placeholder="密码" />
          </Form.Item>
          <Form.Item className={styles.formItem} required help={false}>
            <Input className={styles.input} size="large" name="captcha" placeholder="验证码" />
            <img src={userState.captcha} onClick={() => setUuid(getUUID())} />
          </Form.Item>
          <Form.Item>
            <Form.Submit className={`${styles.button}`} type="primary" validate htmlType="submit" onClick={handleLogin}>
              登录
            </Form.Submit>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
